<?php
namespace Type;

class EventType
{
    const DEFAULT_          = 1;
    const TRIP              = 2;
    const TRAVEL            = 3;
    const HOLIDAY           = 4;
    const SPORT             = 5;
    const ENTERTAINMENT     = 6;
}


namespace Model;

class Events extends \Zend_Db_Table_Abstract
{
    /**
     * @var string
     */
    protected $_name = 'events';
    
    /**
     * @param array $config optional
     */
    public function __construct($config = array())
    {
        parent::__construct($config);
    }
    
    /**
     * Is event (id) exists?
     * 
     * @param int $eventId
     * @return bool
     */
    public function existsId($eventId)
    {
        $stmt = $this->getAdapter()->query(
        "SELECT COUNT(*) AS count
                FROM {$this->_name}
                WHERE id = ?",
        array($eventId));

        $row = $stmt->fetch();
        
        return (bool)$row['count'];
    }
    
    /**
     * Is event (name) exists?
     * 
     * @param int $userId
     * @param string $Name
     * @return bool
     */
    public function existsName($userId, $eventName)
    {
        $stmt = $this->getAdapter()->query(
        "SELECT COUNT(*) AS count
                FROM {$this->_name}
                WHERE userId = ? AND
                `name` = ?",
        array($userId, $eventName));

        $row = $stmt->fetch();
        
        return (bool)$row['count'];
    }
    
    /**
     * Is event exists?
     *
     * @param int $userId
     * @param int $timeStart
     * @param int $timeEnd
     * @return bool 
     */
    public function existsEvent($userId, $timeStart, $timeEnd)
    {
        $stmt = $this->getAdapter()->query(
        "SELECT COUNT(*) AS count
                FROM {$this->_name}
                WHERE userId = ? AND
                timeStart = FROM_UNIXTIME(?) AND
                timeEnd = FROM_UNIXTIME(?);",
        array($userId, $timeStart, $timeEnd));

        $row = $stmt->fetch();
        
        return (bool)$row['count'];
    }
    
    /**
     * Insert an event
     * 
     * @param int $userId
     * @param string $name
     * @param int $type
     * @param int $timeStart
     * @param int $timeEnd
     * @return int
     */
    public function insert( $userId,
                            $name,
                            $type,
                            $timeStart,
                            $timeEnd)
    {   
        $stmt = $this->getAdapter()->query(
        "INSERT INTO {$this->_name} SET
                userId = ?,
                `name` = ?,
                type = ?,
                timeStart = FROM_UNIXTIME(?),
                timeEnd = FROM_UNIXTIME(?);",
        array($userId, $name, $type, $timeStart, $timeEnd));
       
        return $stmt->getDriverStatement()->insert_id;
    }
    
    /**
     * Update an event
     * 
     * @param int $eventId
     * @param string $name
     * @param int $type
     * @param int $timeStart
     * @param int $timeEnd
     * @return int
     */
    public function update( $eventId,
                            $name,
                            $type,
                            $timeStart,
                            $timeEnd)
    {
        $stmt = $this->getAdapter()->query(
        "UPDATE {$this->_name} SET
                id = ?,
                `name` = ?,
                type = ?,
                timeStart = FROM_UNIXTIME(?),
                timeEnd = FROM_UNIXTIME(?);",
        array($eventId, $name, $type, $timeStart, $timeEnd));
       
        return $stmt->getDriverStatement()->affected_rows;
    }
    
    /**
     * Get events by event id
     * 
     * @param int $userId
     * @param int $id
     * @param array $select
     * @return mixed
     */
    public function getEventsById($userId, $id, array $select)
    {
        $selectQuery = implode(',', $select);
        
        $stmt = $this->getAdapter()->query(
        "SELECT {$selectQuery}
                FROM {$this->_name}
                WHERE userId = ? AND
                id = ?;",
        array($userId, $id));
        
        return $stmt->fetchAll();
    }
    
    /**
     * Get events by name
     * 
     * @param int $userId
     * @param string $name
     * @param array $select
     * @return mixed
     */
    public function getEventsByName($userId, $name, array $select)
    {
        $selectQuery = implode(',', $select);
        
        $stmt = $this->getAdapter()->query(
        "SELECT {$selectQuery}
                FROM {$this->_name}
                WHERE userId = ? AND
                `name` = ?;",
        array($userId, $name));
        
        return $stmt->fetchAll();
    }
    
    /**
     * Get events by type
     * 
     * @param int $userId
     * @param string $type
     * @param array $select
     * @return mixed
     */
    public function getEventsByType($userId, $type, array $select)
    {
        $selectQuery = implode(',', $select);
        
        $stmt = $this->getAdapter()->query(
        "SELECT {$selectQuery}
                FROM {$this->_name}
                WHERE userId = ? AND
                type = ?;",
        array($userId, $type));
        
        return $stmt->fetchAll();
    }
    
    /**
     * Get events by datetime interval
     * 
     * @param int $userId
     * @param int $timeStart
     * @param int $timeEnd
     * @param array $select
     * @return mixed
     */
    public function getEventsByDTimeInterval(   $userId,
                                                $timeStart,
                                                $timeEnd,
                                                array $select)
    {
        $selectQuery = implode(',', $select);
        
        $stmt = $this->getAdapter()->query(
        "SELECT {$selectQuery}
                FROM {$this->_name}
                WHERE userId = ? AND 
                ((timeStart >= FROM_UNIXTIME(?) AND
                timeStart <= FROM_UNIXTIME(?)) OR
                (timeEnd >= FROM_UNIXTIME(?) AND
                timeEnd <= FROM_UNIXTIME(?))) 
                ORDER BY timeStart, timeEnd;",
        array($userId, $timeStart, $timeEnd, $timeStart, $timeEnd));
        
        return $stmt->fetchAll();
    }
    
    /**
     * Get events by datetime interval and type
     * 
     * @param int $userId
     * @param int $timeStart
     * @param int $timeEnd
     * @param int $type
     * @param array $select
     * @return mixed
     */
    public function getEventsByTypeAndDTimeInterval($userId,
                                                    $timeStart,
                                                    $timeEnd,
                                                    $type,
                                                    array $select)
    {
        $selectQuery = implode(',', $select);
        
        $stmt = $this->getAdapter()->query(
        "SELECT {$selectQuery}
                FROM {$this->_name}
                WHERE userId = ? AND
                type = ? AND
                timeStart >= FROM_UNIXTIME(?) AND
                timeEnd <= FROM_UNIXTIME(?);",
        array($userId, $type, $timeStart, $timeEnd));
        
        return $stmt->fetchAll();
    }
    
    /**
     * Get max and min time for a user.
     * 
     * @param int $userId
     * @return array minTime, maxTime
     */
    public function getYearInterval($userId) {
        $stmt = $this->getAdapter()->query(
        "SELECT UNIX_TIMESTAMP(MIN(timeStart)) as minTime,
                UNIX_TIMESTAMP(MAX(timeEnd)) as maxTime
                FROM {$this->_name}
                WHERE userId = ?;",
        array($userId));
                
        $result = $stmt->fetch();
        
        if ($result['minTime'] === NULL) {
            $result['minTime'] = $result['maxTime'] = time();
        }
        
        return $result;
    }
    
    /**
     * Returns an array from \Type\EvenType's constants
     * 
     * @return array
     */
    public function getTypes() {
        $typeClass = new \ReflectionClass('\Type\EventType');
            $array = $typeClass->getConstants();
        unset ($typeClass);
        
        return \array_flip($array);
    }
    
    /**
     * Is $date a valid YYYY-MM string?
     * 
     * @param string $date
     * @return boolean
     */
    public function helperIsGetParamDate($date) {
        $tsYear     = \strstr($date, '-', TRUE);
        $tsMonth    = \substr(\strstr($date, '-'), 1);
        
        if (\ctype_digit($tsYear) && \ctype_digit($tsMonth) &&
            \checkdate((int)$tsMonth, 1, (int)$tsYear)) {
            return TRUE;
        }
        
        return FALSE;
    }
}

# eof